<template>
	<div class="form-control">
		<el-form :model="clazz" label-width="auto">
			<el-form-item label="班级名称">
				<el-select v-model="clazz.id" clearable placeholder="请选择班级名称">
					<el-option v-for="item in clazzList" :key="item.id" :label="item.name" :value="item.id"/>
				</el-select>
			</el-form-item>

			<el-form-item label="课程时长">
				<el-input :model-value="clazz.duration" readonly placeholder="请输入课程时长">
					<template #append>周</template>
				</el-input>
			</el-form-item>

			<el-form-item label="班主任">
				<el-input :model-value="clazz.manage_name" type="text" readonly placeholder="请输入班主任名称" />
			</el-form-item>
		</el-form>
		
		<!-- 添加自己的按钮 -->
		<div class="button-container">
			<el-button type="primary" @click="handleSave">保存</el-button>
			<el-button @click="handleClose">关闭</el-button>
		</div>
	</div>

</template>

<script>
import API from '@/api/index.js';

export default {
	data() {
		return {
			clazz: {
				id: null,
				duration: null,
				manage_name: null,
			},
			clazzList: [],
		}
	},

	created() {
		API.clazz_list().then(res => {
			if(res.length === 0) {
				this.$layer.msg("当前没有班级信息，请先创建班级");
				return;
			}else{
				this.clazzList = res;
			}
		})
	},
	methods : {
		handleClose() {
			this.clazz = {
				id: null,
				duration: null,
				manage_name: null,
			};
			this.$emit("close");
		},
		handleSave() {
			if(!this.clazz.id) {
				this.$layer.msg("请选择班级");
				return;
			}
			API.switch_clazz(this.clazz.id).then(res => {
				console.log("切换班级响应:", res);
				this.$layer.msg("切换班级成功");
				this.clazz = {
					id: null,
					duration: null,
					manage_name: null,
				};
				this.$emit("close");
			})
		}
	},

	computed: {
		currentClazz() {
			return this.clazzList.find(item => item.id === this.clazz.id);
		}
	},
	watch: {
		'clazz.id'(newVal) {
			if(newVal) {
				this.clazz.duration = this.currentClazz.duration;
				this.clazz.manage_name = this.currentClazz.manage_name;
			}else{
				this.clazz.duration = null;
				this.clazz.manage_name = null;
			}
		}
	}
}
</script>

<style scoped>
.form-control {
    padding: 30px 30px 10px;
}

.button-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
    gap: 10px;
}
</style>



